<?php
namespace Admin\Model;
use Think\Model\RelationModel;

class LogicClassModel extends RelationModel {

	protected $_validate = array(
		array('id', 'require', '逻辑班级id不能为空！'),
		array('teacher_id', 'require', '教师不能为空!', 1),
		array('course_id', 'require', '课程不能为空！', 1),
		array('class', 'require', '班号不能为空！', 1),
		array('class', 'number', '班号只能是数字！', 1),
	);

	protected $_link = array(
		'teacher' => array(
			'mapping_type'	=> self::BELONGS_TO,
			'class_name'	=> 'Teacher',
			'foreign_key'	=> 'teacher_id',
		),
		'course' => array(
			'mapping_type'	=> self::BELONGS_TO,
			'class_name'	=> 'Course',
			'foreign_key'	=> 'course_id',
		),
		'logic_class_students'	=> array(
		    'mapping_type'  => self::HAS_MANY,
		    'class_name'    => 'LogicClassStudent',
		    'foreign_key'   => 'logic_class_id',
		),
		'homeworks'	=> array(
		    'mapping_type'  => self::HAS_MANY,
		    'class_name'    => 'Homework',
		    'foreign_key'   => 'logic_class_id',
		),
	);

	public function checkUnique($logicClass) {
		$map['teacher_id'] = $logicClass['teacher_id'];
		$map['course_id'] = $logicClass['course_id'];
		$map['class'] = $logicClass['class'];
		$result = $this->where($map)->find();
		return !$result;
	}

	public function hasChildObj($id) {
		$result = $this->where(array('id' => $id))->relation('logic_class_students')->find();
		if($result['logic_class_students']) {
			$this->error = '该逻辑班级下面还有学生，请先删除这些学生！';
			return true;
		}
		$result = array();
		$result = $this->where(array('id' => $id))->relation('homeworks')->find();
		if($result['homeworks']) {
			$this->error = '该逻辑班级下面还有作业，请先删除这些作业！';
			return true;
		}

		return false;
	}

}
